using System.Collections.Generic;
using System.Linq;
using SmartBoard.Core.Element;

namespace SmartBoard.Core.Command
{
    public abstract class BoardCommandManagerBase:IBoardCommandManager
    {
        private readonly IList<ICommand> _commands;
        private readonly IBoardElement _element;

        protected BoardCommandManagerBase(IBoardElement element)
        {
            _commands = new List<ICommand>();
            _element = element;
        }

        public IList<ICommand> Commands
        {
            get { return _commands; }
        }

        public void Register(ICommand command)
        {
            if(command is IRemoteCommandInternal)
            {
                ((IRemoteCommandInternal) command).SetStreamingContext(GetStreamingContext());
            }
            _commands.Add(command);
        }

        private StreamingContext GetStreamingContext()
        {
            return new StreamingContext(_element.StreamManager, _element.DataManager, _element.NetworkServiceModule);
        }

        public void AcceptCommandMessage(int messageId, byte[] payload)
        {
            var command = (from cmd in _commands where cmd is IRemoteCommandInternal && cmd.CommandId == messageId select cmd as IRemoteCommandInternal).FirstOrDefault();
            if (command != null)
            {
                command.Context.RaiseRemoteActionExecuted(payload);
            }
        }
    }
}